package com.solution.admin.home.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.home.constants.IndexConstants;
import com.solution.admin.home.entity.SiteConfigItemEntity;
import com.solution.admin.home.entity.SiteModuleEntity;
import com.solution.admin.home.service.SiteConfigItemService;
import com.solution.admin.home.service.SiteModuleService;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.settings.service.SortService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 网站模块配置项web控制层
 * @author llp
 * @date 2017-09-26 14:46:14
 */
@RequestMapping("/siteConfigItem")
@Controller
public class SiteConfigItemController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SiteConfigItemController.class);

	@Autowired
	private SiteConfigItemService siteConfigItemService;
	
	@Autowired
	private SiteModuleService siteModuleService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private SortService sortService;
	
	/**
	 * 跳转网站模块配置项查询页面
	 * @param SiteConfigItem 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:46:14
	 */
	@RequestMapping("/toListSiteConfigItemPage")
	public String toListSiteConfigItemPage(SiteConfigItemEntity siteConfigItem, HttpServletRequest request) {
		return "home/siteConfigItem_list";
	}

	/**
	 * 分页查询网站模块配置项列表
	 * @param siteConfigItem 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:46:14
	 */
	@RequestMapping("/listSiteConfigItemPage")
	@ResponseBody
	public JSONGrid listSiteConfigItemPage(HttpServletRequest request){
//		int pageNum=1;
//		int numPerPage=10000;
//		PageParam pageParam = super.getPageParam(request);
//		pageParam.setPageNum(pageNum);
//		pageParam.setNumPerPage(numPerPage);
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		// 模块
		String moduleId = request.getParameter("moduleId");
		// 配置标题
		String configTitle = request.getParameter("configTitle");
		// 配置类型
		String configType = request.getParameter("configType");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("moduleId", moduleId);
		paramMap.put("configTitle", configTitle);
		paramMap.put("configType", configType);
		try {
			PageBean pageBean = siteConfigItemService.listSiteConfigItemPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(),pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询网站模块配置项失败", logger, e);
		}
		return new JSONGrid();
	}
	
	/**
	 * 根据商品名称查询商品列表，选择其中一条商品，用于首页楼层中的展示
	 * @param request
	 * @return
	 */
	@RequestMapping("listProductForIndex")
	@ResponseBody
	public JSONGrid listProductForIndex(HttpServletRequest request){
		Map<String, Object> param = new HashMap<String, Object>();
		String productName = request.getParameter("productName");
		if(StringUtil.isNotEmpty(productName)){
			param.put("productName", productName);
			List<ProductEntity> productList = productService.listProductForIndex(param);
			return new JSONGrid(productList,productList.size());
		}else{
			List<ProductEntity> productList = new ArrayList<ProductEntity>();
			return new JSONGrid(productList,productList.size());
		}
	}
	
	
	/**
	 * 跳转新增页面
	 * @return string 跳转页面路径
	 * @author llp
 	 * @date 2017-09-26 14:46:14
	 */
	@RequestMapping("/toAddSiteConfigItem")
	public String toAddSiteConfigItem(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		request.setAttribute("termType", request.getParameter("termType")); //终端类型
		// 查询像所有节点列表，做为父级节点下拉框的选择数据
		List<SiteModuleEntity> smeList = siteModuleService.listSiteModule(null);
		request.setAttribute("smeList", smeList);
		request.setAttribute("moduleId", request.getParameter("moduleId"));
		return "home/siteConfigItem_form";
	}

	/**
	 * 跳转编辑页面
	 * @return string 跳转页面路径
	 * @author llp
 	 * @date 2017-09-26 14:46:14
	 */
	@RequestMapping("/toUpdateSiteConfigItem")
	public String toUpdateSiteConfigItem(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		request.setAttribute("termType", request.getParameter("termType")); //终端类型
		long id = Long.valueOf(request.getParameter("id"));
		try {
			SiteConfigItemEntity siteConfigItem = siteConfigItemService.getSiteConfigItemById(id);
			
			List<String> imageList = new ArrayList<String>();
			if(StringUtil.isNotEmpty(siteConfigItem.getImagePath())){
				String[] imageArr = siteConfigItem.getImagePath().split(",");
				for (String image : imageArr) {
					imageList.add(image);
				}
				siteConfigItem.setImageList(imageList);
			}
			request.setAttribute("siteConfigItem", siteConfigItem);
			List<SiteModuleEntity> smeList = siteModuleService.listSiteModule(null);
			request.setAttribute("smeList", smeList);
		} catch (Exception e) {
			handleException("跳转编辑网站模块配置项页面错误", logger, e);
		}
		return "home/siteConfigItem_form";
	}
	
	
	/**
	 * 启用 停用网站模块配置项
	 * @param request 请求对象
	 * @param siteConfigItemEntity 网站模块配置项实体
	 * @return
	 * @author llp
 	 * @date 2017-09-26 14:46:14
	 */
	@RequestMapping("/saveConfigItemStatus")
	@ResponseBody
	public Map<String, Object> saveConfigItemStatus(HttpServletRequest request, SiteConfigItemEntity siteConfigItemEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			
			if(PublicStatus.STATUS.ENABLED.getId().equals(Integer.parseInt(siteConfigItemEntity.getConfigStatus()))){
				siteConfigItemEntity.setConfigStatus(String.valueOf(PublicStatus.STATUS.DISABLED.getId()));
			}else{
				siteConfigItemEntity.setConfigStatus(String.valueOf(PublicStatus.STATUS.ENABLED.getId()));
			}
			result = siteConfigItemService.updateSiteConfigItem(siteConfigItemEntity);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
			
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("启用 停用网站模块配置项失败", logger, e);
		}
		return resultMap;
	}
	
	
	/**
	 * 删除配置项
	 * @param request
	 * @param siteConfigItemEntity
	 * @return
	 */
	@RequestMapping("/deleteConfigItem")
	@ResponseBody
	public Map<String, Object> deleteConfigItem(HttpServletRequest request, SiteConfigItemEntity siteConfigItemEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String moduleId = request.getParameter("id");
		int result = 0;
		try {
			result = siteConfigItemService.deleteSiteConfigItemById(Long.parseLong(moduleId));
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
			
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("删除网站模块配置项失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 新增或保存网站模块配置项
	 * @param request 请求对象
	 * @param siteConfigItemEntity 网站模块配置项实体
	 * @return
	 * @author llp
 	 * @date 2017-09-26 14:46:14
	 */
	@RequestMapping("/saveOrUpdateSiteConfigItem")
	@ResponseBody
	public Map<String, Object> saveSiteConfigItem(HttpServletRequest request, SiteConfigItemEntity siteConfigItemEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			String[] images = request.getParameterValues("uploadImage");
			StringBuffer tmpBuf = new StringBuffer();
			if(images != null && images.length > 0){
				for (int i = 0 ; i < images.length; i++) {
					if(i != images.length - 1){
						tmpBuf.append(images[i]).append(",");
					}else{
						tmpBuf.append(images[i]);
					}
				}
			}
			siteConfigItemEntity.setImagePath(tmpBuf.toString());
			siteConfigItemEntity.setCreater(getUserName());
			String id = request.getParameter("id");
			if(StringUtil.isNotEmpty(id)){
				result = siteConfigItemService.updateSiteConfigItem(siteConfigItemEntity);
			}else{
				int sortNo = sortService.getFirstSortNo("EB_SITE_CONFIG_ITEM");
				siteConfigItemEntity.setSortNo(sortNo);
				result = (int)siteConfigItemService.saveSiteConfigItem(siteConfigItemEntity);
			}
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
			
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("添加网站模块配置项失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 影响了那块的缓存数据，只刷新某一块的缓存
	 * @param request
	 * @param moduleId
	 * @return Map<String,Object>    
	 * @author xu_cc  
	 * @throws Exception exception
	 * @Date 创建时间：2018年2月26日 下午4:44:58
	 */
	@RequestMapping("/refreshCache")
	@ResponseBody
	public Map<String, Object> refreshCache(HttpServletRequest request, String moduleId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			siteConfigItemService.refreshCache(moduleId);
			resultMap.put(PublicStatus.RESULT_CODE, 1);
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("刷新缓存失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 查询公司联系方式
	 * @param request
	 * @return
	 */
	@RequestMapping("/contact")
	public String getCompanyContact(HttpServletRequest request){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("moduleId", IndexConstants.DB_KEY_SITE_CONFIG_FGINER_CONTACT);
		List<SiteConfigItemEntity> sceList = siteConfigItemService.listSiteConfigItem(param);
		if(sceList != null && sceList.size() >0){
			request.setAttribute("companyContact", sceList.get(0));
		}else{
			request.setAttribute("companyContact", new SiteModuleEntity());
		}
		if("pc".equals(request.getParameter("type"))){
			return "pc/home/pc_contact";
		}
		return "pc/home/contact";
	}
}
